package com.mypack.service;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.MimeMessage.RecipientType;

import com.mypack.dao.ConfigDao;
import com.mypack.dao.EmailDao;
import com.mypack.dao.ManagerDao;
import com.mypack.dao.helper.JpaCallback;
import com.mypack.dao.helper.JpaHelper;
import com.mypack.domain.Config;
import com.mypack.domain.Email;
import com.mypack.domain.Manager;
import com.mypack.exception.ServiceException;

public class CommonService {
	private static CommonService commonService = new CommonService();
	private final Logger logger = Logger.getLogger(getClass().getName());
	
	/**
	 * 超级管理员认证
	 */
	private static final String NAME = "admin", PWD = "admin";
	
	/**
	 * static factory method
	 * get service instance
	 */
	public static CommonService get() {
		return commonService;
	}
	
	public void modifyConfig(final Config config) {
		JpaHelper.doTransation(new JpaCallback() {

			@Override
			public void doInJpa() throws Exception {
				ConfigDao.get().merge(config);
			}
			
		});
	}
	
	public Config findConfigIf() {
		JpaHelper.beginTtransation();
		try {
			return ConfigDao.get().getFirst();
		} finally {
			JpaHelper.endTransaction();
		}
	}
	
	public boolean login(String username, String password) {
		if ((NAME.equals(username) && PWD.equals(password))) {
			logger.info("超级管理员登录");
			return true;
		}
		
		Manager manager = null;
		JpaHelper.beginTtransation();
		try {
			manager = ManagerDao.get().findManagerByName(username);
			if (logger.isLoggable(Level.INFO)) {
				logger.info("登录用户为:" + manager);
			}
		} finally {
			JpaHelper.endTransaction();
		}
		
		if (manager == null) {
			return false;
		}
		
		if (manager.getPassword().equals(password)) {
			return true;
		}
		return false;
	}
	
	public void insertEmail(final Email email) {
		JpaHelper.doTransation(new JpaCallback() {

			@Override
			public void doInJpa() throws Exception {
				EmailDao.get().persist(email);
			}
			
		});
	}
	
	public List<Email> findTop100() {
		JpaHelper.beginTtransation();
		try {
			return EmailDao.get().findAll();
		} finally {
			JpaHelper.endTransaction();
		}
	}

	/**
	 * send email
	 */
	public void sendEmail(String subject) throws ServiceException {
		JpaHelper.beginTtransation();
		final Config config = ConfigDao.get().getFirst();
		JpaHelper.endTransaction();
		
		if (logger.isLoggable(Level.INFO)) {
			logger.info("系统配置 ---> " + config);
		}
		
		if (!config.isFeedbackByEmail()) {
			logger.info("系统配置不用发邮件了,那就不发了吧,呵呵....");
			return;
		}
		
		Properties properties = new Properties();
		properties.put("mail.smtp.host", config.getMailHost()); // "smtp.163.com"
		properties.put("mail.smtp.auth", "true");
		Authenticator authenticator = new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(config.getMailUsername(), config.getMailPassword()); //"yunchow", "qq123456"
			}

		};

		Session session = Session.getDefaultInstance(properties, authenticator);
		session.setDebug(true);
		Message message = new MimeMessage(session);
		try {
			message.setSubject(MimeUtility.encodeText(subject, "GB2312", "B"));
			message.setText(subject);
			message.setFrom(new InternetAddress(config.getMailFrom(), true)); //"yunchow@163.com"
			message.addRecipient(RecipientType.TO, new InternetAddress(config.getMailTo(), true));//"15005193811@139.com"
			Transport.send(message);
			logger.info("发送邮件成功");
		} catch (MessagingException e) {
			throw new ServiceException("send email error.", e);
		} catch (UnsupportedEncodingException e) {
			throw new ServiceException("encode subject text error.", e);
		}
	}

}
